package com.example.component;

import com.example.strategy.ShardingDBConfig;
import com.example.strategy.ShardingTableConfig;
import com.example.utils.CommonUtil;
import org.springframework.stereotype.Component;

import javax.swing.*;

/**
 * @author yinxin
 * @version 1.0
 * @Description:
 * @date 2022/6/814:42
 */
@Component
public class ShortLinkComponent {

    //62进制位数
    public static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 生成短链码
     * @param url
     * @return
     */
    public String createShortLinkCode(String url) {
        long murmurHash = CommonUtil.murmurHash32(url);
        //进制转换为62
        String code = encodeToBase62(murmurHash);
        return ShardingDBConfig.getRandomDBPrefix(code) + code + ShardingTableConfig.getRandomTablePrefix(code);
    }

    /**
     * 测试murmurhash算法
     * @param args
     */
    public static void main(String[] args) {
        ShortLinkComponent shortLinkComponent = new ShortLinkComponent();
        String shortLinkCode = shortLinkComponent.createShortLinkCode("https://blog.csdn.net/exodus520/article/details/90415568");
        System.out.println(shortLinkCode);
    }

    /**
     * 10进制转换成62进制
     * @param num
     * @return
     */
    private String encodeToBase62(long num) {
        //StringBuffer:线程安全  StringBuilder:线程不安全
        StringBuffer sb = new StringBuffer();
        do {
            int i = (int) (num % 62);
            sb.append(CHARS.charAt(i));
            num /= 62;
        } while (num > 0);
        return sb.reverse().toString();
    }


}
